package com.dy.lock.screen.utils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.dy.lock.screen.pojo.UserInfo;
import com.dy.lock.screen.service.UserService;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class CommonUtil {

	private static final Logger log = Logger.getLogger(CommonUtil.class);

	public static final String FILE_SEPARATOR = "/";

	/**
	 * gson格式转换，日期采用yyyy-MM-dd HH:mm:ss格式转换
	 * 
	 * @return
	 */
	public static Gson gson() {
		GsonBuilder gb = new GsonBuilder();
		gb.setDateFormat("yyyy-MM-dd HH:mm:ss");
		gb.disableHtmlEscaping();
		Gson gson = gb.create();
		return gson;
	}

	/**
	 * 潜复制，对不同对象的相同属性进行赋值，被改变的是des
	 * 
	 * @param source
	 * @param desObject目标对象
	 */
	public static void simpleValueCopy(Object source, Object desObject) {
		if (source == null || desObject == null)
			return;
		Method[] sourceMethods = source.getClass().getMethods();
		Method[] desMethods = desObject.getClass().getMethods();
		for (Method m : sourceMethods) {
			String methodName = m.getName();
			if (methodName.startsWith("get")) {
				String methodTmp = methodName.replaceFirst("get", "set");
				for (Method desMethod : desMethods) {
					try {
						if (methodTmp.equals(desMethod.getName())) {
							desMethod.invoke(desObject, m.invoke(source,
									new Object[] {}));
						}
					} catch (Exception e) {
					}
				}
			} else if (methodName.startsWith("is")) {
				String methodTmp = methodName.replaceFirst("is", "set");
				for (Method desMethod : desMethods) {
					try {
						if (methodTmp.equals(desMethod.getName())) {
							desMethod.invoke(desObject, m.invoke(source,
									new Object[] {}));
						}
					} catch (Exception e) {
					}
				}
			}
		}
	}

	/**
	 * 产生六位随机数，前面兩位是日期其他四位是随机数
	 * 
	 * @return
	 */
	public static String createRandomNumber() {
		Integer random = new Random().nextInt(9999);
		if (random != null && random < 1000) {
			random += 1000;
		}
		StringBuffer sb = new StringBuffer();
		sb.append(new SimpleDateFormat("dd").format(new Date()));
		sb.append(random);
		return sb.toString();
	}

	private static final String seed = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

	/**
	 * 产生八位随机数
	 * 
	 * @return
	 */
	public static String createRandomNo(int num) {
		StringBuffer sb = new StringBuffer();
		Random random = new Random();
		for (int i = 0; i < num; i++) {
			sb.append(seed.charAt(random.nextInt(seed.length())));
		}
		return sb.toString().toLowerCase();
	}

	/**
	 * 产生八位数字随机数，前面兩位是日期其他四位是随机数
	 * 
	 * @return
	 */
	public static String createRandomNum() {
		Integer random = new Random().nextInt(999999);
		if (random != null && random < 100000) {
			random += 100000;
		}
		StringBuffer sb = new StringBuffer();
		sb.append(new SimpleDateFormat("dd").format(new Date()));
		sb.append(random);
		return sb.toString();
	}

	private static final BigDecimal THOUSANDS = new BigDecimal("1000");

	/**
	 * 对金额进行除1000操作，默认精确到小数点两位
	 * 
	 * @param money金额
	 * @param scale精度
	 *            小數點的位數
	 * 
	 * @return
	 */
	public static String changeMoney(String money, int scale) {
		try {
			BigDecimal b = new BigDecimal(money).divide(THOUSANDS);
			if (b.toString().indexOf(".") > 0) {
				if (scale <= 0)
					b = b.setScale(2, BigDecimal.ROUND_HALF_UP);
				else
					b = b.setScale(scale, BigDecimal.ROUND_HALF_UP);
			}
			return b.toString();
		} catch (Exception e) {
		}
		return null;
	}

	public static void main(String[] args) {
		Integer i = 11;
		Integer j = 10;
		System.out.println(compare(i, j));
	}

	/**
	 * 提供准确的加法运算
	 * 
	 * @param d1
	 * @param d2
	 * @return
	 */
	public static int add(Integer d1, Integer d2) { // 进行加法运算
		if (d1 == null) {
			d1 = 0;
		}
		if (d2 == null) {
			d2 = 0;
		}
		BigDecimal b1 = new BigDecimal(d1);
		BigDecimal b2 = new BigDecimal(d2);
		return b1.add(b2).intValue();
	}

	/**
	 * 比较大小 d1大于d2 返回true
	 * 
	 * 
	 * @param d1
	 * @param d2
	 * @return
	 */
	public static boolean compare(Integer d1, Integer d2) {
		if (d1 == null) {
			d1 = 0;
		}
		if (d2 == null) {
			d2 = 0;
		}
		BigDecimal b1 = new BigDecimal(d1);
		BigDecimal b2 = new BigDecimal(d2);
		int re = b1.compareTo(b2);
		if (re > 0) {
			return true;
		} else
			return false;
	}

	/**
	 * 提供准确的减法运算
	 * 
	 * @param d1
	 * @param d2
	 * @return
	 */
	public static int sub(Integer d1, Integer d2) { // 进行加法运算
		if (d1 == null) {
			d1 = 0;
		}
		if (d2 == null) {
			d2 = 0;
		}
		BigDecimal b1 = new BigDecimal(d1);
		BigDecimal b2 = new BigDecimal(d2);
		return b1.subtract(b2).intValue();
	}

	public static String getUrlPrefix() {
		Properties p = null;
		try {
			p = readFiles();
		} catch (IOException e) {
			log.error("读取配置文件异常", e);
		}
		return p.get("photo.url.prefix.path").toString();
	}

	public static String getUrlPrefixApi(String key) {
		Properties p = null;
		try {
			p = readFiles();
		} catch (IOException e) {
			log.error("读取配置文件异常", e);
		}
		return p.get(key).toString();
	}

	public static String getPhotoLocation() {
		Properties p = null;
		try {
			p = readFiles();
		} catch (IOException e) {
			log.error("读取配置文件异常", e);
		}
		return p.get("photo.location").toString();
	}

	private static Properties readFiles() throws IOException {
		Properties p = new Properties();
		p.load(CommonUtil.class.getClassLoader().getResourceAsStream(
				"com.properties"));
		return p;
	}

	public static void saveBase64Image(String base64Str, String filePath) {
		if (StringUtils.isNotBlank(base64Str)) {
			// BASE64Decoder decoder = new BASE64Decoder();
			byte[] b;
			try {
				// b = decoder.decodeBuffer(base64Str);
				b = Base64Util.decode(base64Str, Base64Util.DEFAULT);
				for (int i = 0; i < b.length; ++i) {
					if (b[i] < 0) {// 调整异常数据
						b[i] += 256;
					}
				}
				OutputStream out = new FileOutputStream(filePath);
				out.write(b);
				out.flush();
				out.close();
			} catch (IOException e) {
				log.error("生成图片异常", e);
			}
		}
	}

	/**
	 * 把list集合转换成特定字符串
	 * 
	 * @param targetStr
	 * @param regex
	 * @return
	 */
	public static String splitToString(List<String> targetStr, String regex) {
		StringBuilder sb = new StringBuilder();
		if (targetStr != null && !targetStr.isEmpty()) {
			for (String sr : targetStr) {
				sb.append(sr);
				sb.append(";");
			}
			String result = sb.toString();
			return result.substring(0, result.length() - 1);
		} else {
			return "";
		}
	}

	/**
	 * 把指定字符串已指定方式分割，然后在转换成特定字符串
	 * 
	 * @param targetStr
	 * @param regex
	 * @return
	 */
	public static String splitToString(String targetStr, String regex) {
		StringBuilder sb = new StringBuilder();
		String prefix = CommonUtil.getUrlPrefixApi("photo.url.prefix.path.api");
		if (StringUtils.isNotBlank(targetStr)) {
			String[] array = targetStr.split(regex);
			if (array != null) {
				for (String sr : array) {
					sb.append(prefix + sr);
					sb.append(";");
				}
			}
			String result = sb.toString();
			return result.substring(0, result.length() - 1);
		} else {
			return "";
		}
	}

	/**
	 * 根据用户id信息获取用户信息
	 * 
	 * @param userIdStr
	 * @return
	 */
	public static List<UserInfo> getUserListByUserIds(UserService userService,
			String userIdStr) {
		List<UserInfo> list = new ArrayList<UserInfo>();
		if (StringUtils.isNotBlank(userIdStr)) {
			String[] userIds = userIdStr.split(";");
			if (userIds != null) {
				List<String> customerIds = Arrays.asList(userIds);
				Map<String, Object> para = new HashMap<String, Object>();
				para.put("customerIds", customerIds);
				list = userService.getUserListByUserIds(para);
				if (list != null && !list.isEmpty()) {
					for (UserInfo user : list) {
						if (StringUtils.isBlank(user.getUserName())) {
							user.setUserName(user.getUserId());
						}
					}
				}
			}
		}

		return list;
	}
}
